﻿using System.Threading.Tasks;
using Core.Domain.Model;
using NSBus.Dto.Commands;
using NSBus.Server.PushNotification;
using Sanelib.DataOperation;
using Sanelib.Dto.Enumerations;

namespace NSBus.Server.CommandHandlers
{
    public class UpdateUserAuthDataHandler : MessageHandler<UserLoginPostCommand>
    {
        private readonly IRepository<Member> _memberRepository;
        private readonly ISignalRService _signalRService;

        private const int MaxFailedAttempts = 5;

        public UpdateUserAuthDataHandler(IRepository<Member> memberRepository, ISignalRService signalRService, IUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _memberRepository = memberRepository;
            _signalRService = signalRService;
        }

        public override void HandleMessage(UserLoginPostCommand command)
        {
            var member = _memberRepository.GetById(command.UserId);
            if (command.IsAuthSuccess)
            {
                member.FailedAttemptCount = 0;
                member.PasswordRetrievalToken = null;
                member.LastLoginTime = command.LoginDateTime;
                _memberRepository.Update(member);
                Task.Factory.StartNew(() => _signalRService.SendMessage(member.Name + " logged in.", member.Code));
            }
            else
            {
                member.FailedAttemptCount++;
                if (member.FailedAttemptCount >= MaxFailedAttempts) member.UserStatus = UserStatus.Disabled;
                _memberRepository.Update(member);
                Task.Factory.StartNew(() => _signalRService.SendMessage(member.Name + " access failed."));
            }
        }
    }
}
